package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.AdminAutoService;
import com.heima.wemedia.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author lcz
 * @since 2024-11-20
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {


    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private AdminAutoService adminAutoService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult querylist(WmNewsPageReqDto dto) {
        dto.checkParam();
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        Page p = lambdaQuery().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                .like(StringUtils.hasText(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())
                .le(dto.getEndPubDate() != null, WmNews::getCreatedTime, dto.getEndPubDate())
                .ge(dto.getBeginPubDate() != null, WmNews::getCreatedTime, dto.getBeginPubDate())
                .eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId())
                .orderByDesc(WmNews::getCreatedTime)
                .page(page);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(p.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //key = dto.getTitle ,label
        log.info("收到请求：{}", dto);
        if (StringUtils.isEmpty(dto.getTitle()) || StringUtils.isEmpty(dto.getContent())) {
            log.info("参数为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //提取文章内容中的图片
        List<String> contentImages = getContentUrl(dto.getContent());
        //保存文章
        WmNews wmNews = saveNews(dto, contentImages);
        //如果是草稿
        if (dto.getStatus() == WmNews.Status.NORMAL.getCode()) {
            log.info("保存为草稿，不再执行");
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        /**
         * 保存关联关系，预防后续删除
         * 1.保存文章 片和素材的关联关系
         * 2.保存封面图片和素材的关联关系
         *
         */
        saveRelations(contentImages, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);

        String converImages = wmNews.getImages();
        if (!StringUtils.isEmpty(converImages)) {
            String[] coverImages = StringUtils.commaDelimitedListToStringArray(converImages);
            saveRelations(Arrays.asList(coverImages), wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
        adminAutoService.autoScanWmNews(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult changeStatus(WmNewsDto wmNewsDto) {
        //将文章ID传给kafka,根据传入的id查询articleId
        WmNews wmNews = wmNewsMapper.selectById(wmNewsDto.getId());
        Long articleId = wmNews.getArticleId();
        if (articleId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Map<String,Object> map = new HashMap<>();
        Short enable = wmNewsDto.getEnable();
        short statu = (short) (enable == 1 ? 0 : 1);
        wmNews.setEnable(enable);
        wmNewsMapper.updateById(wmNews);
        map.put("articleId", articleId);
        map.put("statu", statu);
        String jsonString = JSON.toJSONString(map);
        kafkaTemplate.send("newStatus", jsonString);
        return ResponseResult.okResult("ok");
    }

    private void saveRelations(List<String> images, Integer id, Short type) {
        if (CollectionUtils.isEmpty(images)) {
            return;
        }
        //通过URL批量去查询id
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmMaterial::getUrl, images);
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        wmNewsMaterialMapper.saveRelations(ids, id, type);
    }

    private WmNews saveNews(WmNewsDto dto, List<String> contentImages) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        List<String> coverImages = getCoverImages(dto, wmNews, contentImages);
        if (!CollectionUtils.isEmpty(coverImages)) {
            //将集合转化为逗号分隔的字符串
            String images = StringUtils.collectionToCommaDelimitedString(contentImages);
            wmNews.setImages(images);
        }
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        save(wmNews);
        return wmNews;
    }

    private List<String> getCoverImages(WmNewsDto dto, WmNews wmNews, List<String> contentImages) {
        List<String> coverImages = dto.getImages();
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            int size = contentImages.size();
            if (size >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                coverImages = contentImages.stream().limit(3).collect(Collectors.toList());
            } else if (size >= 1 && size < 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                coverImages.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }
        return coverImages;
    }


    private List<String> getContentUrl(String content) {
        List<String> images = new ArrayList<>();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            String type = map.get("type").toString();
            if ("image".equals(type)) {
                images.add(map.get("value").toString());
            }
        }
        return images;
    }
}
